package com.zhuang.exception;

import com.alibaba.fastjson.JSON;
import com.zhuang.dto.ResultDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class CommunityExceptionHandle {

    private Logger logger = LoggerFactory.getLogger(CommunityExceptionHandle.class);

    @ExceptionHandler(Exception.class)
    public Object handle(Exception e,
                               HttpServletRequest request,
                               Model model,
                               HttpServletResponse response) {
        StringBuffer requestURL = request.getRequestURL();
        logger.error("exception: {}, url: {}", e, requestURL);

        String contentType = request.getContentType();
        if (contentType.contains("application/json")) {
            ResultDTO resultDTO = null;
            if (e instanceof CustomizeException) {
                 resultDTO = ResultDTO.errorOf((CustomizeException) e);
            } else {
                 resultDTO = ResultDTO.errorOf(CustomizeErrorCode.SYS_ERROR);
            }
            PrintWriter writer = null;
            try {
                response.setContentType("application/json;charset=utf-8");
                writer = response.getWriter();
                writer.write(JSON.toJSONString(resultDTO));
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }


        if (e instanceof CustomizeException) {
            model.addAttribute("message", e.getMessage());
        } else {
            model.addAttribute("message", CustomizeErrorCode.SYS_ERROR.getMessage());
        }
        return new ModelAndView("error");
    }
}
